package com.example.ourradio;

import com.squareup.otto.Subscribe;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class AudioFragment extends Fragment {
	public enum Order {
		SEQUENCE, SINGLE, RANDOM;
	}
	
	private OnFragmentInteractionListener mListener = null;
	private Intent mAudioService = null;
	private Order mOrder = Order.SEQUENCE;

	public AudioFragment() {
		// Required empty public constructor
	}

	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(Utils.STATE_PLAY_ORDER, mOrder);        
    }
	
	 public void onActivityCreated(Bundle savedInstanceState) {
	    super.onActivityCreated(savedInstanceState);
	    if (savedInstanceState != null) {
	    	// Restore last state for checked position.
	        mOrder = (Order)savedInstanceState.getSerializable(
	        	Utils.STATE_PLAY_ORDER
	        );
	    }
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		return inflater.inflate(R.layout.fragment_audio, container, false);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnFragmentInteractionListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnFragmentInteractionListener");
		}
		// Start service	
		mAudioService = new Intent(activity, MediaPlayerService.class);
		mAudioService.setAction(MediaPlayerService.ACTION_CONSTRUCT);
		activity.startService(mAudioService);
		// Register to Bus
		BusManager.getInstance().register(this);
	}

	@Override
	public void onDetach() {
		super.onDetach();
		// Stop service
	    if (mAudioService != null) {
			getActivity().stopService(mAudioService);
			mAudioService = null;
		}
		// Unregister to Bus
	    BusManager.getInstance().unregister(this);
	    // 
		mListener = null;
	}

	@Override
    public void onResume() {
        super.onResume();
        // Restore preferences
	    SharedPreferences settings = 
	    	getActivity().getSharedPreferences(Utils.PREFS_NAME, 0);
	    mOrder = Order.values()[settings.getInt(Utils.STATE_PLAY_ORDER, 0)];
	    initUI();
	}

    @Override
    public void onPause() {
	    super.onPause();
	    // Save preferences
        SharedPreferences settings = 
        	getActivity().getSharedPreferences(Utils.PREFS_NAME, 0);
	    SharedPreferences.Editor editor = settings.edit();
	    editor.putInt(Utils.STATE_PLAY_ORDER, mOrder.ordinal());
	    editor.commit();
	}
	
	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated to
	 * the activity and potentially other fragments contained in that activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnFragmentInteractionListener {
		public void onNextItem(Order order);
		public void onRecordItem();
	}

	public void playMediaPlayAudio(String url) {
		stopAudio();
		
		if (mAudioService == null) {
			return;
		}	
			
		mAudioService.setAction(MediaPlayerService.ACTION_INIT);
		mAudioService.removeExtra(MediaPlayerService.EXTRA_AUDIO_BYTES);
		mAudioService.putExtra(MediaPlayerService.EXTRA_AUDIO_URL, url);
		getActivity().startService(mAudioService);
		
		playAudio();
	}
	
	public void playTTSAudio(String text) {
		stopAudio();
		
        new DownloadTTSTask(getActivity(), this).execute(text);		
	}
	
	public void playTTSAudio(byte[] bytes) {
		mAudioService.setAction(MediaPlayerService.ACTION_INIT);
		mAudioService.removeExtra(MediaPlayerService.EXTRA_AUDIO_URL);
		mAudioService.putExtra(MediaPlayerService.EXTRA_AUDIO_BYTES, bytes);
		getActivity().startService(mAudioService);
		
		playAudio();
	}
	
	public void playAudio() {
		if (mAudioService != null) {
			mAudioService.setAction(MediaPlayerService.ACTION_PLAY);
			getActivity().startService(mAudioService);
			((Button)getActivity().findViewById(R.id.button_play_or_pause))
			 .setEnabled(true);
			((Button)getActivity().findViewById(R.id.button_record))
			 .setEnabled(true);
		} else {
			((Button)getActivity().findViewById(R.id.button_play_or_pause))
			 .setEnabled(false);
			((Button)getActivity().findViewById(R.id.button_record))
			 .setEnabled(false);
		}
	}
	
	public void pauseAudio() {
		if (mAudioService != null) {
			mAudioService.setAction(MediaPlayerService.ACTION_PAUSE);
			getActivity().startService(mAudioService);
		}
	}

	public void stopAudio() {
		if (mAudioService != null) {
			mAudioService.setAction(MediaPlayerService.ACTION_STOP);
			getActivity().startService(mAudioService);
		}
	}
	
	public void nextAudio() {
		if (mListener != null) {
			mListener.onNextItem(Order.SEQUENCE);
		}
	}	
	
	public void recordAudio() {
		stopAudio();
		if (mListener != null) {
			mListener.onRecordItem();
		}
	}
		
	public void playOrder(View view) {
		if (mAudioService != null) {
			mAudioService.setAction(MediaPlayerService.ACTION_ORDER);
			Button button = (Button)view;
			CharSequence text = button.getText();
			if (text == getString(R.string.button_single)) {
				mAudioService.putExtra(
					MediaPlayerService.EXTRA_AUDIO_ORDER,
					Order.RANDOM
				);
				button.setText(R.string.button_random);
				mOrder = Order.RANDOM;
			} else if (text == getString(R.string.button_random)) {
				mAudioService.putExtra(
					MediaPlayerService.EXTRA_AUDIO_ORDER,
					Order.SEQUENCE
				);
				button.setText(R.string.button_sequence);
				mOrder = Order.SEQUENCE;
			} else if (text == getString(R.string.button_sequence)) {
				mAudioService.putExtra(
					MediaPlayerService.EXTRA_AUDIO_ORDER,
					Order.SINGLE
				);
				button.setText(R.string.button_single);
				mOrder = Order.SINGLE;
			}   
			getActivity().startService(mAudioService);
		}
	}	

	@Subscribe 
	public void updateUI(DownloadTTSTask.Status ttsStatus) {
		if (mListener != null) {
			mListener.onNextItem(mOrder);
		}			
	}
		
	@Subscribe 
	public void updateUI(AudioStatus audioStatus) {
		AudioState audioState = audioStatus.mAudioState;
		Button button_play_or_pause = 
	   		(Button)getActivity().findViewById(R.id.button_play_or_pause);
		if (null != button_play_or_pause) {
	        if (audioState == AudioState.STARTED) {
	           	button_play_or_pause.setText(R.string.button_pause);
	           	button_play_or_pause.setOnClickListener(
	           		new View.OnClickListener() {
	           			@Override
	           			public void onClick (View v) {
	           				pauseAudio();
	           			}
	           		}	
	           	);
	        } else if (audioState == AudioState.PAUSED ||
	        		   audioState == AudioState.STOPPED ||
	        		   audioState == AudioState.COMPLETED) {
	            button_play_or_pause.setText(R.string.button_play);
		        button_play_or_pause.setOnClickListener(
		        	new View.OnClickListener() {
		        		@Override
	            		public void onClick (View v) {
	            			playAudio();
	            		}
	            	}	
		        );
	        } 
		}
		
		if (audioState == AudioState.COMPLETED) {
			if (mListener != null) {
				mListener.onNextItem(mOrder);
			}			
		}
    }
	
	public void onTTSComplete() {
		if (mListener != null) {
			mListener.onNextItem(mOrder);
		}
	}
	
	private void initUI() {
		Button button_play_or_pause = 
			(Button)getActivity().findViewById(R.id.button_play_or_pause);
		button_play_or_pause.setOnClickListener(
	    	new View.OnClickListener() {
	    		@Override
	    		public void onClick (View v) {
	    			playAudio();
	    		}
	    	}	
	      );
		button_play_or_pause.setEnabled(false);
		
		Button button_play_order = 
			(Button)getActivity().findViewById(R.id.button_play_order);
		button_play_order.setOnClickListener(
	    	new View.OnClickListener() {
	    		@Override
	    		public void onClick (View v) {
	    			playOrder(v);
	    		}
	    	}	
	    );
		
		switch (mOrder) {
		case SEQUENCE: 
			button_play_order.setText(R.string.button_sequence);
			break;
		case SINGLE:
			button_play_order.setText(R.string.button_single);
			break;
		case RANDOM:
			button_play_order.setText(R.string.button_random);
			break;
		}
		
		((Button)getActivity().findViewById(R.id.button_stop))
	     .setOnClickListener(
	    	new View.OnClickListener() {
	    		@Override
	    		public void onClick (View v) {
	    			stopAudio();
	    		}
	    	}	
	    );
		
		((Button)getActivity().findViewById(R.id.button_next))
	     .setOnClickListener(
	    	new View.OnClickListener() {
	    		@Override
	    		public void onClick (View v) {
	    			nextAudio();
	    		}
	    	}	
	    );
		
		Button button_record = 
			((Button)getActivity().findViewById(R.id.button_record));
		button_record.setOnClickListener(
	    	new View.OnClickListener() {
	    		@Override
	    		public void onClick (View v) {
	    			recordAudio();
	    		}
	    	}	
	    );
		button_record.setEnabled(false);
		
	}
}